package com.trans.handler;

import com.trans.anno.Translator;
import com.trans.auxiliary.HandleFullRecord;
import com.trans.auxiliary.HandleRecord;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *@Description TODO
 *@Author xwduo
 *@Date 2022年03月01日 08:51
 **/
@Slf4j
public class Array implements TranslateHandle<String,Map<String,String>> {

    public static final String PREFIX = "LOCAL_DICT:";

    @Override
    @SuppressWarnings("unchecked")
   public Object doHandle(HandleRecord record, Map<String, Map<String,String>> cacheMap) {
        Object curItemVal = record.getVal();
        if(null != curItemVal){
            String value = String.valueOf(curItemVal);
            Object o = cacheMap.get(record.fieldName);
            if(null != o){
                Map<String,Object> val = (Map<String, Object>) o;
                return String.valueOf(val.getOrDefault(value,value));

            }
        }
        return null;
    }

    @Override
    public Map<String, Map<String,String>> cache(List<HandleFullRecord> recordList) {
        Map<String,Map<String,String>> params = new HashMap<>();
        for (HandleFullRecord handleFullRecord : recordList) {
            Translator translator = handleFullRecord.translator;
            List<String> dicText = fetchParams(translator.extraParams(),PREFIX);
            String name = handleFullRecord.params.name;
            if(!params.containsKey(name)){
                Map<String,String> nameCache = new HashMap<>();
                for (int i = 0; i < dicText.size(); i++) {
                    String s = dicText.get(i);
                    nameCache.put(String.valueOf(i),s);
                }
                if(!nameCache.isEmpty()){
                    params.put(name,nameCache);
                }
            }
        }
        return  params;

    }

    @Override
    public int order() {
        return 0;
    }

}
